<template>
    <div class="container text-center">
        <div class="row">
            <div class="col">
                <div class="input-group">
                    <input type="text" class="form-control" list="searchDatalistOptions" placeholder="关键字" v-model="key" aria-label="关键字"
                        aria-describedby="button-query-topic">
                    <button type="button" class="btn btn-outline-secondary" @click="query" id="button-query-topic"
                        :disabled="key.length <= 0">查找帖子</button>
                    <datalist id="searchDatalistOptions">
                      <option :value="item" v-for="item in keys" :key="item"/>
                    </datalist>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col">
                <ol class="list-group">
                    <li class="list-group-item list-group-item-action overflow-hidden" v-for="item in items"
                        :key="item.id">
                        <topicItem :item="item"></topicItem>
                    </li>
                </ol>
            </div>
        </div>
        <div class="row" v-show="page.total > 0">
            <pagination @pageto="pageto" :total_count="page.total" :total_page="page.pages" :pageno="page.index"
                :count="page.size"></pagination>
        </div>
    </div>
</template>
<script lang="ts" setup>
    import { reactive, ref } from "vue";
    import { getCurrentTab, sendMessage, localSave, localStorage } from "@/utils/api"
    import pagination from '@/components/pagination.vue';
    import topicItem from '@/components/topicItem.vue';
    import { Reactive, Ref } from "@vue/reactivity";
    import type {ComponentInternalInstance} from "vue"
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const key : Ref<string> = ref("")
    const keys: Reactive<string[]> = reactive([])
    const hostname : Ref<string> = ref("haijiao.com")
    const items : Reactive<any[]> = reactive([])
    const page : Reactive<any> = reactive({
        "total": 0,
        "pages": 1,
        "index": 1,
        "size": 15
    })
    
    watch(key, async (newValue, _) => {
        if (newValue.length <= 0) return
        
        const localObj = await localStorage().get("search")
        if (!localObj['search']) return
        if (!localObj['search'].keys.includes(newValue)) return
        keys.splice(keys.indexOf(newValue), 1)
        keys.unshift(newValue)
        localObj['search'].keys.splice(0, localObj['search'].keys.length, ...keys)
        await localSave('search', localObj['search'])

        const topics = localObj['search'].topics[newValue]
        
        items.splice(0, items.length, ...topics.results)
        page.total = topics.page.total
        page.index = topics.page.page
        page.size = topics.page.limit
        page.pages = Math.ceil(topics.page.total / topics.page.limit)
    })


    const props = defineProps({
        url: {
            type: String,
            default: '',
        },
    })
    onMounted(async () => {
        const localObj = await localStorage().get("search")
        if (localObj['search']?.keys) {
            keys.splice(0, keys.length, ...localObj['search'].keys)
        }
        if (!key.value && keys.length > 0) {
            key.value = keys[0]
        }
        
    })
    const query = async () => {
        await pageto(1)
        console.log(items, page)
    }
    const openUrlWithNewTab = async (url : string) => {
        console.log(url)
        const resp = await sendMessage({ action: 'openTabWithUrl', url: url });
        console.log(resp)
    }
    const pageto = async (index: number) => {
        const { topics, error } = await sendMessage({ action: 'search', params: { key: key.value, page: index, node_id: 0 } })
        console.log(topics, error)
        if (!topics || !topics.results) {
            proxy?.$toast(`search: ${error}`)
            return
        }
        // await localSave(key.value, { topics })
        
        await saveSearchTopics(key.value, topics)
        items.splice(0, items.length, ...topics.results)
        page.total = topics.page.total
        page.index = topics.page.page
        page.size = topics.page.limit
        page.pages = Math.ceil(topics.page.total / topics.page.limit)
        
    }
    /**
     * 保存key,topics到search
     */
    const saveSearchTopics = async (newValue: string, topics: any) => {
        if (!newValue || newValue.length <= 0) return
        const localObj = await localStorage().get("search")
        if (!localObj['search']) {
            localObj['search'] = {keys: [], 'topics': {}}
        }
        if (keys.includes(newValue)) {
            keys.splice(keys.indexOf(newValue), 1)
        }
        keys.unshift(newValue)
        localObj['search'].keys.splice(0, localObj['search'].keys.length, ...keys)
        localObj['search'].topics[newValue] = topics
        await localSave('search', localObj['search'])
    }
</script>